package com.hrb.monkey.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.hrb.monkey.R;
import com.hrb.monkey.activity.base.BaseActivity;
import com.hrb.monkey.activity.expand.ExpandActivity;
import com.hrb.monkey.frament.CustomViewFragment;
import com.hrb.monkey.frament.FirstFragment;
import com.hrb.monkey.frament.LoginFragment;
import com.hrb.monkey.frament.OneArticleFragment;
import com.hrb.monkey.frament.SecondFragment;
import com.hrb.monkey.frament.ThirdFragment;
import com.hrb.monkey.utils.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 应用的主页面
 */
public class MainActivity extends BaseActivity {

    @BindView(R.id.toolsBar)
    Toolbar toolsBar;
    @BindView(R.id.nav_view)
    public NavigationView navView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.content_fragment)
    FrameLayout contentFragment;

    FirstFragment firstFragment;
    SecondFragment secondFragment;
    ThirdFragment thirdFragment;
    LoginFragment loginFragment;
    CustomViewFragment customViewFragment;
    OneArticleFragment oneArticleFragment;
    Fragment[] fragments;
    int lastFragment;//记录选中的fragment；
    ActionBar actionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ToastUtil.init(getApplication());
        appStartPage();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        /*加载顶部菜单*/
        ButterKnife.bind(this);
        setSupportActionBar(toolsBar);
        actionBar= getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
        }
        initFragment();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case R.id.toolsBar_setting:
//                Toast.makeText(this, "设置", Toast.LENGTH_LONG).show();
                Intent intent =new Intent(this,ExpandActivity.class);
                startActivity(intent);
                break;
            case R.id.toolsBar_refresh:
                Toast.makeText(this, "刷新", Toast.LENGTH_LONG).show();
                break;
            case R.id.toolsBar_return:
                Toast.makeText(this, "返回", Toast.LENGTH_LONG).show();
                break;
            case android.R.id.home:
                drawerLayout.openDrawer(Gravity.START);//点击顶部左侧菜单键 抽屉弹出
                break;
        }
        return true;
    }
    /**初始化fragment部分*/
    private void initFragment(){
            firstFragment=new FirstFragment();
            secondFragment=new SecondFragment();
            thirdFragment =new ThirdFragment();
            loginFragment=new LoginFragment();
            customViewFragment=new CustomViewFragment();
            oneArticleFragment=new OneArticleFragment();
            fragments=new Fragment[]{firstFragment,secondFragment,thirdFragment,loginFragment,customViewFragment,oneArticleFragment};
            getSupportFragmentManager().beginTransaction().replace(R.id.content_fragment,firstFragment).show(firstFragment).commit();
            //设置默认选中项
            navView.setCheckedItem(R.id.nav_setting);
            /**绑定抽屉菜单改变事件*/
            navView.setNavigationItemSelectedListener(drawerItemChange);


    }
    /*抽屉菜单中选中项改变时调用事件*/
    private NavigationView.OnNavigationItemSelectedListener drawerItemChange=new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            drawerLayout.closeDrawers();
            //Toast.makeText(getBaseContext(), menuItem.getTitle(), Toast.LENGTH_SHORT).show();
            switch (menuItem.getItemId()){
                case R.id.nav_setting:
                {
                    if(lastFragment!=0){
                        switchFragment(lastFragment,0);
                        lastFragment=0;
                        actionBar.show();
                    }
                    return true;
                }
                case R.id.nav_refresh:
                {
                    if(lastFragment!=1){
                        switchFragment(lastFragment,1);
                        lastFragment=1;
                        actionBar.show();
                    }
                    return true;
                }
                case R.id.nav_pay:
                {
                    if(lastFragment!=2){
                        switchFragment(lastFragment,2);
                        lastFragment=2;
                        actionBar.hide();
                    }
                    return true;
                }
                case R.id.nav_login:
                {
                    if(lastFragment!=3){
                        switchFragment(lastFragment,3);
                        lastFragment=3;
                        actionBar.hide();
                    }
                    return true;
                }
                case R.id.nav_component:
                {
                    if(lastFragment!=4){
                        switchFragment(lastFragment,4);
                        lastFragment=4;
                        actionBar.hide();
                    }
                    return true;
                }
                case R.id.nav_OneArticle:
                {
                    if(lastFragment!=5){
                        switchFragment(lastFragment,5);
                        lastFragment=5;
                        actionBar.hide();
                    }
                    return true;
                }

            }

            return false;
        }
    };

    /**
     *
     * @param lastFragment 上次的fragment序号
     * @param index 要切换的fragme
     */
    private void switchFragment(int lastFragment,int index){
        FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
        transaction.hide(fragments[lastFragment]);
        if(fragments[index].isAdded()==false){
            transaction.add(R.id.content_fragment,fragments[index]);
        }
        transaction.show(fragments[index]).commitAllowingStateLoss();
    }
    public  void switchFragment(int lastFragment,int index, Bundle bundle1){
        FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
        transaction.hide(fragments[lastFragment]);
        if(fragments[index].isAdded()==false){
            transaction.add(R.id.content_fragment,fragments[index]);
        }
        fragments[index].setArguments(bundle1);
        transaction.show(fragments[index]).commitAllowingStateLoss();
        this.lastFragment=3;
    }
    private  void  appStartPage(){
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                //  Initialize SharedPreferences
                SharedPreferences getPrefs = PreferenceManager
                        .getDefaultSharedPreferences(getBaseContext());

                //  Create a new boolean and preference and set it to true
                boolean isFirstStart = getPrefs.getBoolean("firstStart", true);

                //  If the activity has never started before...
                if (isFirstStart) {

                    //  Launch app intro
                    final Intent i = new Intent(MainActivity.this, IntroActivity.class);

                    runOnUiThread(new Runnable() {
                        @Override public void run() {
                            startActivity(i);
                        }
                    });

                    //  Make a new preferences editor
                    SharedPreferences.Editor e = getPrefs.edit();

                    //  Edit preference to make it false because we don't want this to run again
                    //e.putBoolean("firstStart", false);
                    e.putBoolean("firstStart", false);

                    //  Apply changes
                    e.apply();
                }
            }
        });

        // Start the thread
        t.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("mainActivity","onResume");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("mainActivity","onStart");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("mainActivity","onStop");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("mainActivity","onPause");
    }
}
